<script>
let billComponent =  {
    template: `
<div id="tallyRecordBox">
    <div class="el-row">
        <div class="el-col el-col-8 el-col-xs-24">
            <div style="background: rgb(241, 82, 58);position: relative;border-radius: 4px;padding: 20px;margin: 0 5px;height: 100px;box-sizing: border-box;color: #fff;font-size: 14px;">
            <h1 style="font-size:32px;font-weight: bold;">{{ monthCountDebt.in }}</h1>
                <div class="value">本月收入</div>
            </div>
        </div>
        <div class="el-col el-col-8 el-col-xs-24">
            <div style="background: rgb(103, 194, 58);position: relative;border-radius: 4px;padding: 20px;margin: 0 5px;height: 100px;box-sizing: border-box;color: #fff;font-size: 14px;">
            <h1 style="font-size:32px;font-weight: bold;">{{ monthCountDebt.out }}</h1>
                <div class="value">本月支出</div>
            </div>
        </div>
        <div class="el-col el-col-8 el-col-xs-24">
            <div style="background: rgb(64, 158, 255);position: relative;border-radius: 4px;padding: 20px;margin: 0 5px;height: 100px;box-sizing: border-box;color: #fff;font-size: 14px;">
            <h1 style="font-size:32px;font-weight: bold;">{{ monthCountDebt.debt }}</h1>
                <div class="value">本月利润</div>
            </div>
        </div>
   </div>
    <div class="tallyRecordForm">
        <div class="recordListBox">
            <el-card class="box-card" style="cursor: initial;">
                <div slot="header" class="clearfix">
                    <span>账目清单</span>
                    <el-divider direction="vertical"></el-divider>
                    <span>{{ recordPeriod }}</span>
                    <div class="recordStatRight">
                        总收入：
                        <span class="orange number" id="ft-payout">+{{ recordCountDebt.in }}</span>
                        <el-divider direction="vertical"></el-divider>
                        总支出：
                        <span class="green number" id="ft-payout">-{{ recordCountDebt.out }}</span>
                        <el-divider direction="vertical"></el-divider>
                        利润：
                        <span class="blue number" id="ft-payout">{{ recordCountDebt.debt }}</span>
                        <el-divider direction="vertical"></el-divider>
                        未入账：
                        <span class="gray number" id="ft-payout">{{ recordCountDebt.check }}</span>
                    </div>
                </div>
                <div class="recordSearchBox" style="cursor: initial;">
                    <el-form :inline="true" v-model="recordSearchForm" class="form-inline recordSearchForm">
            <el-form-item size="mini">
            <el-select placeholder="全部类型" clearable filterable default-first-option v-model="recordSearchForm.type" @change="recordSearchForm.category_id='';" filterable>
            <el-option
            v-for="item in tallyTypes"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
                <el-cascader
                     collapse-tags clearable
                     v-model="recordSearchForm.category_id"
                     :options="categoryListForOptions"></el-cascader>
            </el-form-item>
            <el-form-item size="mini">
            <el-select   placeholder="全部账户" multiple  collapse-tags clearable filterable default-first-option v-model="recordSearchForm.accounts" @change="selectDisposeCode">
            <el-option
            v-for="item in accountList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select placeholder="客户/供应商" multiple  collapse-tags clearable filterable default-first-option v-model="recordSearchForm.stores" @visible-change="checkCateValid" @change="selectDisposeCode">
            <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select multiple  collapse-tags placeholder="项目" clearable filterable default-first-option v-model="recordSearchForm.projects" @change="selectDisposeCode">
            <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select multiple  collapse-tags  placeholder="员工" clearable filterable default-first-option v-model="recordSearchForm.members" @change="selectDisposeCode">
            <el-option
            v-for="item in memberList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select  placeholder="状态" clearable filterable default-first-option v-model="recordSearchForm.state"">
            <el-option
            v-for="item in stateList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-date-picker class="datePicker" type="date" value-format="yyyy-MM-dd" placeholder="开始日期" v-model="recordSearchForm.begin_date"></el-date-picker>
            ~
            <el-date-picker class="datePicker" type="date" value-format="yyyy-MM-dd" placeholder="结束日期" v-model="recordSearchForm.end_date"></el-date-picker>
            </el-form-item>
            <el-form-item size="mini">
            <el-input placeholder="备注关键字" v-model="recordSearchForm.memo"></el-input>
            </el-form-item>
            <el-button type="primary" size="mini" @click="handleRecordPageChange(1)"><i class="el-icon-search" /> 检索</el-button>
            <el-divider direction="vertical"></el-divider>
            <!--<el-button type="primary" size="mini" @click="getRecordList(1)">最近三个月</el-button>
            <el-divider direction="vertical"></el-divider>-->
            <el-button type="success" size="mini" @click="exportRecordList()"><i class="el-icon-download" />  导出</el-button>
        </el-form>
        </div>
        <div class="recordTable">
        <template>
        <el-table :data="recordList" border stripe  style="cursor: initial;">
        <el-table-column fixed type="index">
        </el-table-column>
        <el-table-column prop="tally_time" sortable width="150" label="账单日期">
        <template slot-scope="scope">
        <p><i class="el-icon-time"></i>
        <span>{{ scope.row.tally_time.substring(0,10) }}</span>
        </p>
        <p>{{ scope.row.type_txt}} -{{ scope.row.category_name }} </p>
        </template>
        </el-table-column>
        <el-table-column prop="account_name" label="账户/金额">
        <template slot-scope="scope">
        <p v-if="scope.row.type==10" class="amount-in">
        + <span>{{ scope.row.amount }}</span>
        </p>
        <p v-if="scope.row.type==20" class="amount-out">
        - <span>{{ scope.row.amount }}</span>
        </p>
        <p v-if="scope.row.type==30" class="amount-trans">
        <span>{{ scope.row.amount }}</span>
        </p>
        <p v-if="scope.row.type==30">{{ scope.row.account_name}} <i class="el-icon-right"></i> {{ scope.row.account_dst_name}} </p>
        <p v-else>{{ scope.row.account_name}} </p>
        </template>
        </el-table-column>
        <el-table-column prop="store_name" width="100px" label="客户/供应商"></el-table-column>
        <el-table-column prop="project_name" label="项目"></el-table-column>
        <el-table-column prop="project_name" label="材料">
        <template slot-scope="scope" v-if="scope.row.material_json!= ''">
            <a href="javascript:" style="color: skyblue" @click="lookMaterial(scope.row.material_json)">查看材料</a>
        </template>
        </el-table-column>
        <el-table-column prop="member_name" label="员工"></el-table-column>
        <el-table-column prop="memo" label="备注"></el-table-column>
        <el-table-column prop="extra" label="附件">
        <template slot-scope="scope">
        <span v-for="(item,iai) in scope.row.attachment" >
        <a :href="item.file_name" target="_blank" class="attachLink">
        附{{ ++iai }}
        </a>&nbsp;
        </span>
        </template>
        </el-table-column>
        <el-table-column prop="state_txt" label="状态">
        <template slot-scope="scope">
            <el-tag v-if="scope.row.state == '1'" type="success" size="mini">{{scope.row.state_txt}}</el-tag>
            <el-tag v-if="scope.row.state == '0'" type="info" size="mini">{{scope.row.state_txt}}</el-tag>
            <el-tag v-if="scope.row.state == '-1'" type="warning" size="mini">{{scope.row.state_txt}}</el-tag>
        </template>
        </el-table-column>
        <el-table-column prop="uid_name" label="会计">
        <template slot-scope="scope">
        {{scope.row.uid_name}}
        </el-popover>
           
        </template>
        </el-table-column>
        <el-table-column prop="state_txt" label="审核"  v-if="currentTally.role!='accountant' && currentTally.role!='viewer' ">
        <template slot-scope="scope">
        <div v-if="scope.row.state==0 && currentTally.role!='accountant'" >
        <span class="recordOptBtn primary" @click="auditRecord(scope.row,1)">
        <i class="el-icon-check"></i>&nbsp;</span>
        <span class="recordOptBtn primary" @click="auditRecord(scope.row,-1)">
        <i class="el-icon-close"></i>&nbsp;</span>
        </div>
        <div v-if="scope.row.state==1" >
        {{scope.row.audit_name}}
        </el-popover>
        
        </div>
        </template>
        </el-table-column>
        <el-table-column fixed="right" width="100" label="操作" v-if="currentTally.role!='cashier' && currentTally.role!='viewer' ">
        <template slot-scope="scope">
        <span class="recordOptBtn primary" @click="editRecord(scope.row)" style="cursor: pointer;">
        <i class="el-icon-edit"></i>&nbsp;
        </span>
        <span class="recordOptBtn danger" v-if="!(scope.row.state!=0 && currentTally.role=='accountant')" @click="delRecord(scope.$index,scope.row)" style="cursor: pointer;">
        <i class="el-icon-delete-solid"></i>&nbsp;
        </span>
        </template>
        </el-table-column>
        </el-table>

        <p style="margin-top: 10px;text-align: center">
        <el-pagination
        :current-page="currentPage"
        background
        layout="prev, pager, next, total"
        :page-size="recordListPage.pageSize"
        :total="recordListPage.totalCount"
        @current-change="handleRecordPageChange"
        >
        </el-pagination>
        </p>

        </template>
        </div>
        </el-card>
        </div>
    </div>
    <!--账单编辑表单框------>
    <record-form :dialogShow="recordDialog" :formRow="recordForm" @modalClose="modalClose" @getRecordList="getRecordList"></record-form>
       <!-- 查看材料   -->
    <look-material-details :dialogShow="lookMaterialDetailsDialog" :recordList="material_json_data"   @modalClose="lookMaterialModalClose"></look-material-details>

</div>
    `,
    computed: {
        currentTallyId() {
            return this.$store.state.currentTallyId
        },
        currentTally () {
            return this.$store.state.currentTally
        },
        customList () {
            return this.$store.state.customList
        },
        gysList () {
            return this.$store.state.gysList
        },
        storeList() {
            if(this.recordSearchForm.type===10) return this.customList
            if(this.recordSearchForm.type===20) return this.gysList
        },
        categoryListIn() {
            return this.$store.state.categoryListIn
        },
        categoryListOut() {
            return this.$store.state.categoryListOut
        },
        categoryList() {
            if(this.recordSearchForm.type===10) return this.categoryListIn
            if(this.recordSearchForm.type===20) return  this.categoryListOut
            return [];
        },
        accountList() {
            return this.$store.state.accountList
        },
        projectList() {
            return this.$store.state.projectList
        },
        memberList() {
            return this.$store.state.memberList
        },
        categoryListForOptions(){
            let options = []
            let origin_datas = this.categoryList;
            for (let i=0;i<origin_datas.length;i++){
                if(origin_datas[i]['children']===undefined){
                    continue;
                }
                let itemData = {
                    'label':origin_datas[i]['title'],
                    'value':origin_datas[i]['id'],
                    'children':[]
                };
                for (let a = 0;a<origin_datas[i]['children'].length;a++){
                    let itemVItem = {
                        'label':origin_datas[i]['children'][a]['title'],
                        'value':origin_datas[i]['children'][a]['id'],
                    };
                    if(origin_datas[i]['children'][a]['children'] !== undefined){
                        itemVItem['children'] = [];
                        for (let z=0;z<origin_datas[i]['children'][a]['children'].length;z++){
                            itemVItem['children'].push({
                                'label':origin_datas[i]['children'][a]['children'][z]['title'],
                                'value':origin_datas[i]['children'][a]['children'][z]['id'],
                            });
                        }
                    }
                    itemData['children'].push(itemVItem);
                }
                options.push(itemData);
            }
            console.log(options)
            return options;
        },
        stateList() {
            return [
                {"id":0,"name":'待审核'},
                {"id":1,"name":'已入账'},
                {"id":-1,"name":'被拒绝'},
            ];
        }
    },
    data:function(){
        return {
            material_json_data:[],
            material_lists:[],
            lookMaterialDetailsDialog:false,
            recordDialog:false,
            recordForm:{},
            currentPage:1,
            recordCountDebt:{
                in : 0.00 ,
                out : 0.00 ,
                debt : 0.00 ,
                check : 0.00,
            },
            monthCountDebt:{
                in : 0.00 ,
                out : 0.00 ,
                debt : 0.00 ,
            },
            recordPeriod: monthBeginDate + ' ～ '+monthEndDate,
            recordSearchForm:{
                begin_date : monthBeginDate,
                end_date : monthEndDate,
            },
            tallyTypes:[{id:10,title:'收入'},{id:20,title:'支出'},{id:30,title:'转账'}],
            recordList:[],
            recordListPage:{
                pageSize:10,
                totalCount:0,
            },
        }
    },
    mounted () {
        this.initData()
    },
    methods:{
        lookMaterial(json_data){
            console.log(json_data)
            if(json_data == ''){
                this.material_json_data = []
            }else{
                this.material_json_data = JSON.parse(json_data)
            }
            this.lookMaterialDetailsDialog = true
        },
        lookMaterialModalClose(){
            this.lookMaterialDetailsDialog = false;
        },
        initData() {
            this.getRecordList()
        },
        modalClose(){
            this.recordDialog = false
        },
        selectDisposeCode(){
            this.$forceUpdate()
        },
        handleRecordPageChange(currentPage){
            this.currentPage = currentPage
            this.getRecordList(0)
        },
        checkCateValid(viState){
            if(viState && !this.recordSearchForm.type) {
                this.$message({
                    type: 'info',
                    message: '请先选择类型'
                })
            }
        },
        getRecordList(an,type = 1){
            let that = this
            let page = this.currentPage

            console.log("升级")

            var date = new Date();
            console.log(date)
            if(an === 1) {
                that.recordSearchForm = {
                    begin_date : monthBeginDate,
                    end_date : monthEndDate,
                }
            }
            if(that.recordSearchForm['category_id'] != undefined){
                that.recordSearchForm['category_id'] = that.recordSearchForm['category_id'][that.recordSearchForm['category_id'].length-1];
            }
            that.recordSearchForm.tally_id = that.currentTallyId




            that.recordSearchForm.page = page
            axios.get('/api/tally-record/lists',{
                method: 'get',
                headers: {'token': loginToken},
                params: that.recordSearchForm
            }).then(function(res) {
                if(res.data.status === 'success'){
                    that.recordList = res.data.data.data
                    that.recordPeriod = that.recordSearchForm.begin_date + ' ～ '+ that.recordSearchForm.end_date
                    that.recordListPage = res.data.data.pageInfo
                }else{
                    that.$message({
                        type: 'error',
                        message: '解析数据失败:'+res.data.error_message
                    })
                }
            })
            // 获取债务统计
            axios.get('/api/tally-record/count-debt',{
                method: 'get',
                headers: {'token': loginToken},
                params: that.recordSearchForm
            }).then(function(res) {
                if(res.data.status === 'success'){
                    that.recordCountDebt = res.data.data
                }else{
                    that.$message({
                        type: 'error',
                        message: '解析数据失败:'+res.data.error_message
                    })
                }
            })
            // 获取本月债务统计
            axios.get('/api/tally-record/month-debt',{
                method: 'get',
                headers: {'token': loginToken},
                params: that.recordSearchForm
            }).then(function(res) {
                if(res.data.status === 'success'){
                    that.monthCountDebt = res.data.data
                }else{
                    that.$message({
                        type: 'error',
                        message: '解析数据失败:'+res.data.error_message
                    })
                }
            })
        },
        exportRecordList(){
            let that = this
            that.recordSearchForm.tally_id = that.currentTallyId
            axios.get('/api/tally-record/export',{
                method: 'get',
                headers: {'token': loginToken},
                params: that.recordSearchForm
            }).then(function(res) {
                if(res.data.status === 'success'){
                    let filepath = res.data.data.filepath
                    let a = document.createElement('a');
                    a.target = "_blank";
                    a.href = filepath;
                    a.click();
                    console.log(res.data)
                }else{
                    that.$message({
                        type: 'error',
                        message: '解析数据失败:'+res.data.error_message
                    })
                }
            })
        },
        editRecord(row){
            let editRow = JSON.parse(JSON.stringify(row))
            if(editRow['tally_time'] !== '' ){
                let timeArr = editRow.tally_time.split(' ')
                editRow.dateR = timeArr[0]
                editRow.timeR = timeArr[1]
            }
            editRow.category_id = String(editRow.category_id )
            editRow.account_id = String(editRow.account_id )
            if(editRow.member_id  === 0) editRow.member_id = ''
            if(editRow.store_id  === 0) editRow.store_id = ''
            if(editRow.account_dst_id  === 0) editRow.account_dst_id = ''
            if(editRow.project_id  === 0) editRow.project_id = ''
            editRow.member_id = String(editRow.member_id )
            editRow.store_id = String(editRow.store_id )
            editRow.account_dst_id = String(editRow.account_dst_id )
            editRow.project_id = String(editRow.project_id )
            // 处理附件转换
            this.recordFormEditFileList=[]
            editRow.attachment.forEach(v=>{
                this.recordFormEditFileList.push({
                    name:v.id,
                    url:v.file_name
                })
            });
            if(editRow.material_json !== ''){
                editRow.material_json = JSON.parse(editRow.material_json);
            }else{
                editRow.material_json = []
            }
            this.recordForm = editRow
            this.recordDialog = true
        },
        auditRecord(row,state){
            let that = this
            let advice = state === 1 ? '同意' : '拒绝'
            let state_txt = state === 1 ? '已入账' : '已忽略'
            this.$confirm('确定要审核该行记录：'+ advice, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    if(action === 'confirm') {
                        let postUrl = '/api/tally-record/audit'
                        axios.post(postUrl,{id:row.id,state:state},{
                            headers: {'token': loginToken},
                        }).then(function(res) {
                            if(res.data.status === 'success'){
                                row.state = state
                                row.state_txt = state_txt
                                that.$message({
                                    type: 'success',
                                    message: '操作成功~'
                                })
                            }else{
                                that.$message({
                                    type: 'error',
                                    message: '解析数据失败:'+res.data.error_message
                                })
                            }
                        })
                    }
                }
            });
        },
        delRecord(index,row){
            let that = this
            this.$confirm('确定要删除该行记录', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    if(action === 'confirm') {
                        let postUrl = '/api/tally-record/del'
                        axios.post(postUrl,{id:row['id']},{
                            headers: {'token': loginToken},
                        }).then(function(res) {
                            if(res.data.status === 'success'){
                                that.$message({
                                    type: 'success',
                                    message: '操作成功~'
                                })
                                that.recordList.splice(index, 1)
                            }else{
                                that.$message({
                                    type: 'error',
                                    message: '解析数据失败:'+res.data.error_message
                                })
                            }
                        })
                    }
                }
            })
        }
    }
}
</script>
